<template>
	<view>
		<uni-popup ref="popup" type="center">
			<view class="popup-content">
				<view class="popup-title">{{addressId?'编辑收货地址':'添加收货地址'}}</view>
				<uni-forms :label-width="90" ref="form" :modelValue="addressForm" :rules="formRules">
					<uni-forms-item required label="姓名" name="userName">
						<uni-easyinput type="text" v-model="addressForm.userName" placeholder="请输入姓名" />
					</uni-forms-item>
					<uni-forms-item required label="手机号" name="phone">
						<uni-easyinput type="text" v-model="addressForm.phone" placeholder="请输入手机号" />
					</uni-forms-item>
					<uni-forms-item required label="所在地区" name="city">
						<uni-easyinput type="text" v-model="addressForm.city" placeholder="请输入所在地区" />
					</uni-forms-item>
					<uni-forms-item required label="详细地址" name="addressDetail">
						<view class="address-position">
							<uni-easyinput disabled type="text" v-model="addressForm.addressDetail" placeholder="请输入详细地址" />
							<uni-icons @click="chooseAddress" type="location"></uni-icons>
						</view>
					</uni-forms-item>
				</uni-forms>
				<!-- <view class="form-item">
					<view class="form-label">姓名</view>
					<view class="form-con">
						<input placeholder-class="placeholder-class" class="form-con" type="text"
							v-model="addressForm.userName" placeholder="请输入收货人姓名" />
					</view>
				</view>
				<view class="form-item">
					<view class="form-label">手机号</view>
					<view class="form-con">
						<input placeholder-class="placeholder-class" class="form-con" type="tel"
							v-model="addressForm.phone" placeholder="请输入收货人手机号" />
					</view>
				</view>
				<view class="form-item">
					<view class="form-label">所在地区</view>
					<view class="form-con">
						<input placeholder-class="placeholder-class" type="tel" v-model="addressForm.city"
							placeholder="请选择所在地区" />
					</view>
				</view>
				<view class="form-item flex-start">
					<view class="form-label">详细地址</view>
					<view class="form-con" @click="chooseAddress">
						<textarea auto-height placeholder-class="placeholder-class" class="form-textarea" type="tel"
							v-model="addressForm.addressDetail" placeholder="请输入详细地址" />
					</view>
				</view> -->
				<button class="add-btn" type="primary" @click="submitAddress">保存</button>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	const addressObj = uniCloud.importObject('address')
	export default {
		name: "address-popup",
		props: {
			type: String
		},
		data() {
			return {
				formRules: {
					userName: {
						rules: [{
							required: true,
							errorMessage: '请填写姓名'
						}]
					},
					phone: {
						rules: [
							{
								required: true,
								errorMessage: '请输入手机号',
							},
							{
								validateFunction: function(rule, value, data, callback) {
									const reg = /^\d{10}6$/
									console.log(reg.test(value))
									if (!reg.test(value)) {
										callback('请输入正确的手机号')
									}
									return true
								}
							}
						]
					},
					city: {
						rules: [{
							required: true,
							errorMessage: '请填写所在地区'
						}]
					},
					addressDetail: {
						rules: [{
							required: true,
							errorMessage: '请选择详细地址'
						}]
					}
				},
				addressId: '',
				addressForm: {
					userName: '',
					phone: '',
					city: '',
					addressDetail: '',
					addressInfo: {
						latitude: '',
						longitude: ''
					}
				}
			};
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.formRules)
		},
		methods: {
			async submitAddress() {
				this.$refs['form'].validate().then(async res => {
					console.log('success', res);
					uni.showToast({
						title: `校验通过`
					})

					let params = {
						userName: this.addressForm.userName,
						phone: this.addressForm.phone,
						city: this.addressForm.city,
						address: this.addressForm.addressDetail,
						addressInfo: {
							latitude: this.addressForm.addressInfo?.latitude,
							longitude: this.addressForm.addressInfo?.longitude
						}
					}
					//提交地址数据
					if (this.type === 'cloudFunc') {
						if (this.addressId) {
							params._id = this.addressId
						}
						console.log(params)
						let res = await addressObj.saveData({
							...params
						})
						console.log(res)
						if (res.code === 200) {
							this.$refs.popup.close()
							this.$emit("success-callback")
						}
					} else {
						if (!this.addressId) {
							this.$parent.$refs.udb.add({
								...params
							}, {
								toastTitle: '新增成功', // toast提示语
								success: (res) => { // 新增成功后的回调
									this.$refs.popup.close()
									this.$parent.$refs.udb.refresh()
								}
							})
						} else {
							this.$parent.$refs.udb.update(this.addressId, {
								...params
							}, {
								toastTitle: '保存成功', // toast提示语
								success: (res) => { // 新增成功后的回调
									this.$refs.popup.close()
									this.$parent.$refs.udb.refresh()
								}
							})
						}
					}
				}).catch(err => {
					console.log('err', err);
				})

			},
			doCitySelect() {
				console.log('citySelect')
				const key = 'XKFBZ-EGZWI-J6JGV-UDHT7-IREKV-KGBYC'; //使用在腾讯位置服务申请的key
				const referer = 'bwclass'; //调用插件的app的名称
				const hotCitys = '北京'; // 用户自定义的的热门城市
				wx.navigateTo({
					url: `plugin://citySelector/index?key=${key}&referer=${referer}&hotCitys=${hotCitys}`,
				})
			},
			openMap(info) {
				uni.chooseLocation({
					latitude: info.latitude,
					longitude: info.longitude,
					success: (res) => {
						// console.log(res);
						// console.log('位置名称：' + res.name);
						// console.log('详细地址：' + res.address); 
						// // 经度
						// console.log('经度：' + res.longitude);
						// // 纬度
						// console.log('纬度：' + res.latitude);
						this.addressForm.addressDetail = res.address + res.name
						this.addressForm.addressInfo = {
							latitude: res.latitude,
							longitude: res.longitude
						}
					},
					fail() {

					}
					// 成功回调
				})
			},
			chooseLocation() {
				console.log(111)
				const that = this
				// 先判断定位权限是否开启
				if (this.addressForm.addressInfo?.latitude && this.addressForm.addressInfo?.longitude) {
					this.openMap({
						latitude: this.addressForm.addressInfo.latitude,
						longitude: this.addressForm.addressInfo.longitude
					})
				} else {

					uni.getLocation({
						success(result) {
							console.log(result)
							// 定位权限开启，打开地图
							that.openMap(result)
						},
						fail(e) {
							// 定位权限未开启，引导设置
							uni.showModal({
								title: '温馨提示',
								content: '您已拒绝定位,请开启',
								confirmText: '去设置',
								success(res) {
									if (res.confirm) {
										//打开授权设置
										openSetting()
									}
								}
							})
						}
					})
				}
			}, //打开授权设置（必须用户点击小程序才能打开授权设置，所以前面加了showModel）
			openSetting() {
				// 打开小程序的设置
				// #ifdef MP-WEIXIN
				uni.openSetting()
				// #endif
				// App跳转系统的设置界面
				// #ifdef APP-PLUS
				uni.getSystemInfo({
					success(res) {
						if (res.platform == 'ios') {
							//IOS
							plus.runtime.openURL("app-settings://");
						} else if (res.platform == 'android') {
							//安卓
							let main = plus.android.runtimeMainActivity();
							let Intent = plus.android.importClass("android.content.Intent");
							let mIntent = new Intent('android.settings.ACTION_SETTINGS');
							main.startActivity(mIntent);
						}
					}
				});
				// #endif
			},
			childOpen(id) {
				if (id) {
					this.addressId = id
					this.getAddressDetail()
				} else {
					this.addressId = ''
					this.addressForm = {
						userName: '',
						phone: '',
						city: '',
						addressDetail: '',
						addressInfo: {
							latitude: '',
							longitude: ''
						}
					}
				}
				this.$refs.popup.open()
			},
			//获取地址详情用作回显
			async getAddressDetail() {
				let res = await addressObj.getDetail({
					_id: this.addressId
				})
				console.log(res)
				if (res.data.length >= 1) {
					let addressInfo = res.data[0]
					this.addressForm = {
						userName: addressInfo.userName,
						phone: addressInfo.phone,
						city: addressInfo.city,
						addressDetail: addressInfo.address,
						addressInfo: addressInfo.addressInfo
					}
				}
			},
			chooseAddress() {
				/**
				 
				// #ifdef MP-WEIXIN
				const key = 'XKFBZ-EGZWI-J6JGV-UDHT7-IREKV-KGBYC'; //使用在腾讯位置服务申请的key
				const referer = 'bwclass'; //调用插件的app的名称
				const location = JSON.stringify({
				  latitude: 39.89631551,
				  longitude: 116.323459711
				});
				const category = '生活服务,娱乐休闲';
				uni.navigateTo({
				  url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}&category=${category}`
				});
				// #endif
				// #ifdef H5
					// uni.navigateTo({
					// 	url:'/pages/map/map'
					// })
					// uni.chooseLocation({
					// 	success: function (res) {
					// 		console.log('位置名称：' + res.name);
					// 		console.log('详细地址：' + res.address);
					// 		console.log('纬度：' + res.latitude);
					// 		console.log('经度：' + res.longitude);
					// 	}
					// });
					location.href="https://map.qq.com/?type=marker&isopeninfowin=1&markertype=1&name=%E4%B8%AD%E5%9B%BD%2C%E5%8C%97%E4%BA%AC%E5%B8%82%2C%E5%8C%97%E4%BA%AC%E5%B8%82%2C%E8%A5%BF%E5%9F%8E%E5%8C%BA&addr=%E7%9F%B3%E7%A2%91%E8%83%A1%E5%90%8C&pointy=39.904956&pointx=116.389449&coord=39.904956%2C116.389449&ref=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"
				// #endif
				*
				*/
				this.chooseLocation()

			}
		}
	}
</script>

<style lang="scss">
	.popup-content {
		background: #fff;
		width: 710rpx;
		padding: 30rpx;
		box-sizing: border-box;
		border-radius: 10rpx;

		.popup-title {
			text-align: center;
			font-weight: bold;
			margin-bottom: 20rpx;
		}
		.address-position{
			display: flex;
			align-items: center;
		}
		.form-item {
			display: flex;
			border-bottom: 1rpx solid #CCC;
			padding: 30rpx 0;
			font-size: 30rpx;
			align-items: center;

			&.flex-start {
				align-items: flex-start;
			}

			.form-label {
				width: 130rpx;
				text-align: left;
				color: #777;
				flex-shrink: 0;
			}

			.form-con {
				flex: 1;
				font-size: 30rpx;
			}

			.form-textarea {
				width: auto;
			}

			.placeholder-class {
				color: #AAA;
			}
		}
	}
</style>